<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\LitestoreShop;
use fast\Random;
use think\Request;
use think\Db;
use think\Validate;
use app\common\model\User as UserModel;
use app\common\library\Sms as Smslib;
/**
 * 会员接口
 */
class User extends Api
{

    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {

        $site=\think\config::get('site');
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password)
        {
            $this->error(config('message.Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);

        if ($ret)
        {
            if(!empty($site['down_integral'])){
                $down_integral=$site['down_integral'];
            }else{
                $down_integral=0;
            }
            $userOne=$this->auth->getUser();
            $UserSerice=new \app\common\service\User();
            $UserSerice->FirstDownlod($userOne['id'],$down_integral);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(config('message.Logged in successful'), $data);
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile 手机号
     * @param string $password 密码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $password = $this->request->request('password');
        if (!$mobile || !$password)
        {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$"))
        {
            $this->error(__('Mobile is incorrect'));
        }

        $Auth = new Auth();

        $user = \app\common\model\User::getByMobile($mobile);

        if ($user->password == $Auth->getEncryptPassword($password, $user->salt) )
        {
            $this->error("密码不正确");
        }
        if ($user)
        {
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        }
        else
        {
            $code = randomkeys(4);
            $ret = $this->auth->register($mobile, Random::alnum(), $code, $mobile, []);
        }
        if ($ret)
        {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->auth->upToken();
            $this->success(__('Logged in successful'), $data);
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $mobile 手机号
     * @param string $password 密码
     * @param string $code 邀请码
     * @param string $captcha 手机验证码
     */

    public function register()
    {
        $site=\think\config::get('site');
        $UserSerice=new \app\common\service\User();
        $mobile = $this->request->request('account');
        $password = $this->request->request('password');
        $code = $this->request->request('code');
//        $longitude= $this->request->request('longitude'); //经度114.03289881
//        $latitude = $this->request->request('latitude'); //纬度 22.64382712
//        $code = randomkeys(4);
        $captcha = $this->request->request('captcha');
        if (!$password)
        {
            $this->error(config('message.Password is incorrect'));
        }
        if (!$code)
        {
            $this->error(config('message.Code is incorrect'));
        }
        if (!$captcha)
        {
            $this->error(config('message.Captcha is incorrect'));
        }
        $Usercode  = \app\common\model\User::where(array('code'=>$code))->find();
        if(empty($Usercode->code)){
            $this->error(config('message.User_code_error'));
        }
        if( $Usercode->code != $code){
                $this->error(config('message.User_code_error'));
         }
        $parent_id  = $Usercode->id;
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$"))
        {
            $this->error(config('message.Mobile is incorrect'));
        }
        $event = 'register';
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $userinfo = UserModel::getByMobile($mobile);

        if ($event == 'register' && $userinfo) {
            //已被注册
            $this->error(__('已被注册'));
        } else if (in_array($event, ['changemobile']) && $userinfo) {
            //被占用
            $this->error(__('已被占用'));
        } else if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
            //未注册
            $this->error(__('未注册'));
        }
        $ret = Smslib::check($mobile, $captcha, $event);

        if ($ret) {
            $username = $mobile.' ';
            $new_code = initcode();
            $ret = $this->auth->register($username, $password, $new_code, $mobile, [],$parent_id);
            if ($ret)
            {
                $user=$this->auth->getUser();
                $userServer=new \app\common\service\User();
                $userServer->getAgentId($user->id);
                $userOne=$this->auth->getUser();
                if(!empty($site['down_integral'])){
                    $down_integral=$site['down_integral'];
                }else{
                    $down_integral=0;
                }

                if(!empty($site['recommended_score'])){
                    $recommended_score=$site['recommended_score'];
                }else{
                    $recommended_score=0;
                }

                if(!empty($site['scan_score'])){
                    $scan_score=$site['scan_score'];
                }else{
                    $scan_score=0;
                }

                $UserSerice->IntegrallnsInfo($userOne['id'],$scan_score,$recommended_score,$down_integral);

//                if(!empty($latitude)&&!empty($longitude)){
//
//                    $cityList=getCityList(trim($latitude).','.trim($longitude));
//
//                    if(!empty($cityList)){
//                        $province=Db::name('area')->where(['name'=>$cityList['province']])->find();
//                        $areadata['province']=$province['id'];
//
//                        $city=Db::name('area')->where(['name'=>$cityList['city']])->find();
//                        $areadata['city']=$city['id'];
//
//                        $district=Db::name('area')->where(['name'=>$cityList['district']])->find();
//                        $areadata['area']=$district['id'];
//
//                        Db::name('user')->where(['id'=>$userOne['id']])->update($areadata);
//                    }
//
//                }else{

                if(cookie('cache_location_city')){

                    $area=cookie('cache_location_city');
                    $province=Db::name('area')->where(['name'=>$area['province']])->find();
                    $areadata['province']=$province['id'];

                    $city=Db::name('area')->where(['name'=>$area['city']])->find();
                    $areadata['city']=$city['id'];

                    $district=Db::name('area')->where(['name'=>$area['district']])->find();
                    $areadata['area']=$district['id'];

                    Db::name('user')->where(['id'=>$userOne['id']])->update($areadata);
                }
//                }


                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Sign up successful'), $data);
            }
            else
            {
                $this->error($this->auth->getError());
            }
        } else {
            $this->error(__('验证码不正确'));
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar');
        $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
        if ($exists)
        {
            $this->error(__('Username already exists'));
        }
        $user->username = $username;
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha)
        {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email"))
        {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find())
        {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result)
        {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $email 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha)
        {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$"))
        {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find())
        {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result)
        {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform]))
        {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result)
        {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret)
            {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $mobile = $this->request->request("mobile");
        $newpassword = $this->request->request("newpassword");
        $confirmpassword = $this->request->request("confirmpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha)
        {
            $this->error(config('message.newpassword_captcha'));
        }

            if (!Validate::regex($mobile, "^1\d{10}$"))
            {
                $this->error(config('message.Mobile is incorrect'));
            }
            if(!$confirmpassword){
                $this->error(config('message.confirmpassword_message'));
            }
            if($newpassword !=$confirmpassword ){
                $this->error(config('message.newpassword_confirmpassword'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user)
            {
                $this->error(config('message.resetpwd_user_no'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret)
            {
                $this->error(config('message.Captcha_iserror'));
            }
            Sms::flush($mobile, 'resetpwd');

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret)
        {
            $this->success(config('message.Reset_password_successful'));
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 商家支付
     */
    public  function qrcodet(){
      try{
          $shop=new LitestoreShop();
          $shopSerice=new \app\common\service\LitestoreShop();
          $user=$this->auth->getUser();
          $user_id=(int)$user['id'];
          $shopList=$shop->where(['user_id'=>$user_id])->find();
          $data['img']='/'.$shopSerice->createcode((int)$shopList->id).'?v='.time();
          $data['res_point']=$shopList->res_point;
      }catch (\Exception $e){
            $this->error('获取支付二维码不存在!');
      }
      $this->success('获取成功!',$data);
    }



}
